<?php
	function check_valid_user($u) {
		$sql = sprintf("SELECT * FROM `t_drivers` WHERE `netid` = %s",quote_smart($u));
		$result = mysql_query($sql);
		printMYSQLDebug($sql,$result);
		if ( (mysql_num_rows($result) != 1)  ) 
			return false;
		return true;
	}
	
	function check_allow_login($u) {
		$sql = sprintf("SELECT `allow_login` FROM `t_drivers` WHERE `netid` = %s AND `allow_login` = 1",quote_smart($u));
		$result = mysql_query($sql);
		printMYSQLDebug($sql,$result);
		if ( (mysql_num_rows($result) != 1)  ) 
			return false;
		return true;
	}
	
	function local_auth_user($u,$p) {
		$sql = sprintf("SELECT `password` FROM `t_drivers` WHERE `netid` = %s AND `password` = MD5(%s)",quote_smart($u),quote_smart($p));
		$result = mysql_query($sql);
		printMYSQLDebug($sql,$result);
		if ( (mysql_num_rows($result) != 1)  ) 
			return false;
		return true;
	}
	
	function checkQualified() {
		$required = func_get_arg(0);
		$numargs = func_num_args();

		if ($numargs >= 2) {
			$permission = func_get_arg(1);
		} else { //just use the current user's
			$permission = $_SESSION['permission'];
		}
		$req_piece = preg_split('//', $required,-1,PREG_SPLIT_NO_EMPTY);
		$cur_piece = preg_split('//', $permission,-1,PREG_SPLIT_NO_EMPTY);

		if($required >= 1000) {
			//check for ams and admins here
			if(($req_piece[0] == 1) and (($cur_piece[0] == 1) or ($cur_piece[0] == 3) or ($cur_piece[0] == 5) or ($cur_piece[0] == 7))) {
				return true;
			} else if(($req_piece[0] == 2) and (($cur_piece[0] == 2) or ($cur_piece[0] == 3) or ($cur_piece[0] == 6) or ($cur_piece[0] == 7))) {
				return true;
			} else if(($req_piece[0] == 4) and (($cur_piece[0] == 4) or ($cur_piece[0] == 5) or ($cur_piece[0] == 6) or ($cur_piece[0] == 7))) {
				return true;
			} else {
				return false;
			}		
		} else if ($required >= 100) {
			//check for dispatch, pm and training
			if(($req_piece[1] == 1) and (($cur_piece[1] == 1) or ($cur_piece[1] == 3) or ($cur_piece[1] == 5) or ($cur_piece[1] == 7))) {
				return true;
			} else if(($req_piece[1] == 2) and (($cur_piece[1] == 2) or ($cur_piece[1] == 3) or ($cur_piece[1] == 6) or ($cur_piece[1] == 7))) {
				return true;
			} else if(($req_piece[1] == 4) and (($cur_piece[1] == 4) or ($cur_piece[1] == 5) or ($cur_piece[1] == 6) or ($cur_piece[1] == 7))) {
				return true;
			} else {
				return false;
			}		
		} else if ($required >= 10) {
			//check for buckland and storrs/mansfield
			if(($req_piece[2] == 1) and (($cur_piece[2] == 1) or ($cur_piece[2] == 3) or ($cur_piece[2] == 5) or ($cur_piece[2] == 7))) {
				return true;
			} else if(($req_piece[2] == 2) and (($cur_piece[2] == 2) or ($cur_piece[2] == 3) or ($cur_piece[2] == 6) or ($cur_piece[2] == 7))) {
				return true;
			} else if(($req_piece[2] == 4) and (($cur_piece[2] == 4) or ($cur_piece[2] == 5) or ($cur_piece[2] == 6) or ($cur_piece[2] == 7))) {
				return true;
			} else {
				return false;
			}		
		} else if ($required >= 1) {
			//check for trainee, buswash and shuttle
			if(($req_piece[3] == 1) and (($cur_piece[3] == 1) or ($cur_piece[3] == 3) or ($cur_piece[3] == 5) or ($cur_piece[3] == 7))) {
				return true;
			} else if(($req_piece[3] == 2) and (($cur_piece[3] == 2) or ($cur_piece[3] == 3) or ($cur_piece[3] == 6) or ($cur_piece[3] == 7))) {
				return true;
			} else if(($req_piece[3] == 4) and (($cur_piece[3] == 4) or ($cur_piece[3] == 5) or ($cur_piece[3] == 6) or ($cur_piece[3] == 7))) {
				return true;
			} else {
				return false;
			}
		} else {
			//check if the person is eligible to sign up
			if($cur_piece[3] > 0) {
				return true;
			} else {
				return false;
			}
		}
	}

	function errorText ($text) {
		printDebug($text,LVL_ERROR);
	}
		
	function printMYSQLError($result) {
		printDebug("A database error occurred. It has been logged.",LVL_ERROR,"MySQL says '" . mysql_error() . " (" . mysql_errno() . ")'",1);
	}
	
	function printMYSQLDebug($query,$result) {
		printDebug("SQL QUERY: " . $query . "<br>\n" . 'RESULTS: ' . @mysql_num_rows($result),
				LVL_DEBUG);
	}
	
	function printDebug() { 
		if(func_num_args() == 1) {
			$reason = func_get_arg(0);
			$level = constant("LVL_DEBUG");
		}
		if(func_num_args() >= 2) {
			$reason = func_get_arg(0);
			$level = func_get_arg(1);
		}
		if(func_num_args() >= 3)
			$debug = func_get_arg(2);
		if(func_num_args() >= 4) {
			if(func_get_arg(3) == 1) {
				$systemError = 1;
			} else {
				$systemError = 0;
			}
		} else {
			$systemError = 0;
		}
			
		if($level <= constant("ERROR_LOGGING")) {
			$sql = sprintf("INSERT INTO `errors` (`error_type`,`system_error`,`description`,`debug_info`,`user_id`,`error_time`) VALUES (%s,%s,%s,%s,%s,%s)",quote_smart($level),quote_smart($systemError),quote_smart($reason),quote_smart($debug),quote_smart($_SESSION['driver_id']),time());
			$result = mysql_query($sql);
			$errorLogging = "<BR>ERN: " . strtoupper(dechex(mysql_insert_id()));
		}
				
		if(SYSTEM_MODE < $level) return;
		switch ($level) {
			case 1: //errors
				?>
					<div style="margin:20px; font-size:10px; background-color:#FFCECE; border: 1px solid #FF2222; padding: 10px; text-align:center; font-weight: bold;"><?=displayIcon(ICON_ERROR)?>&nbsp;&nbsp;&nbsp;&nbsp;<?= $reason ?><?= $errorLogging?></div>	
				<?php
				break;
			case 2: //warnings
				?>
					<div style="margin:20px; font-size:10px; background-color:#FFCECE; border: 1px solid #FF2222; padding: 10px; text-align:left; font-family:'Courier New', Courier, mono; font-weight:none;"><strong>WARNING: </strong><?= $reason ?><?= $errorLogging?></div>	
				<?php
				break;
			case 5: //info
				?>
					<div style="margin:20px; font-size:10px; background-color:#CECEFF; border: 1px solid #000080; padding: 10px; text-align:left; font-family:'Courier New', Courier, mono; font-weight:none;"><strong>INFO: </strong><?= $reason ?><?= $errorLogging?></div>	
				<?php
				break;
			default: //debug
				?>
					<div style="margin:20px; font-size:10px; background-color:#FFFFCC; border: 1px solid #000000; padding: 10px; text-align:left; font-family:'Courier New', Courier, mono; font-weight: none;"><strong>DEBUG: </strong><?= $reason ?><?= $errorLogging?></div>	
				<?php
		}
	}

	function alertText ($text) {
		?>
		<div style="margin:20px; background-color:#FFFFCC; border: 1px solid #FFFF00; padding: 10px; text-align:center; font-weight: bold;"><?= $text ?></div>
		<?php
	}
	
	function alertSuccess ($text) {
		?>
		<div style="margin: 10px auto 10px auto; width: 400px; background-color:#D1D2FA; border: 1px solid #000000; padding: 10px; text-align:center; font-weight: bold; font-size: 12px;"><?= displayIcon(ICON_ACCEPT) ?>&nbsp;&nbsp;&nbsp;&nbsp;<?= $text ?></div>
		<?php
	}
	
	function isDispatcher() {
		if($_SESSION['is_dispatcher'] == 1) return true;
		return false;
	}
	
	function signupTime ($signupID, $driverID) {
		printDebug("Verifying signup time");
		$select = sprintf("SELECT * FROM `t_sched_signups` WHERE `t_sched_signups`.`signup_id` = %s AND `t_sched_signups`.`driver_id` = %s",quote_smart($signupID),quote_smart($driverID));
		$sql = mysql_query($select);
		printMYSQLDebug($select,$sql);
		if($sql === false) {
			printDebug("Error finding signup time.",LVL_ERROR,'DB Error. MySQL said: ' . mysql_errno() . " " . mysql_error(),1);
			return false;
		}
		if(@mysql_num_rows($sql) == 0) {
			printDebug("Tried to verify signup time, but no signup time exists.");
			return false;
		}
		if($row = @mysql_fetch_assoc($sql)) {
			$date = $row['date'];
			$time = $row['time'];
			$signup_time = mktime(substr($time,0,2),substr($time,2,2),0,substr($date,4,2),substr($date,6,2),substr($date,0,4));
			if($signup_time > time()) {
			  //the signup time is greater than the current time.. which means no!
			  printDebug("Your signup time has not yet come.");
			  return false;
			} else {
			  //the signup time is smaller than the current time.. yup
			  printDebug("Signup time has come.");
			  return true;
			}
		} else {
			return false;
		}
	}

	// Quote variable to make safe
	function quote_smart($value) {
	   // Stripslashes
	   if (get_magic_quotes_gpc()) {
		   $value = stripslashes($value);
	   }
	   
	   // if null, return
	   if ($value == 'NULL') {
			return($value);
	   }
	   
	   // Quote if not integer
	   if (!is_numeric($value)) {
		   $value = "'" . mysql_escape_string($value) . "'";
	   }
	   return $value;
	}

	function subtractTime($time,$subtractAmt) {
		$time = sprintf("%04d",$time);
		$subtractAmt = sprintf("%04d",$subtractAmt);
		$minute_answer = (substr($time,0,2) * 60 + substr($time,2,2)) - (substr($subtractAmt,0,2) * 60 + substr($subtractAmt,2,2));
		$hours = floor($minute_answer / 60);
		$minutes = $minute_answer - ($hours * 60);
		return sprintf("%02d",$hours) . sprintf("%02d",$minutes);
	}

	function addTime($time,$subtractAmt) {
		$time = sprintf("%04d",$time);
		$subtractAmt = sprintf("%04d",$subtractAmt);
		$minute_answer = (substr($time,0,2) * 60 + substr($time,2,2)) + (substr($subtractAmt,0,2) * 60 + substr($subtractAmt,2,2));
		$hours = floor($minute_answer / 60);
		$minutes = $minute_answer - ($hours * 60);
		return sprintf("%02d",$hours) . sprintf("%02d",$minutes);
	}

	function formatOutputTime($timeIn) {
		//all i do is take in a time, make sure that it is valid 24hr time and output it as 4 digits
		if($timeIn >= 2400) {
			$timeIn -= 2400;
		}
		return padOutputTime($timeIn);
	}

	function padOutputTime($timeIn) {
		//all i do is pad output time
		return sprintf("%04d",$timeIn);
	}

	function paylogTime ($time) {
		$hour = substr($time,0,2);
		$minute = substr($time,2,2);
		if($minute < 8) {
			return $hour;
		} elseif ($minute < 23) {
			return $hour + .25;
		} elseif ($minute < 38) {
			return $hour + .5;
		} elseif ($minute < 53) {
			return $hour + .75;
		} else {
			return $hour + 1;
		}
	}
	
	function displayDriverSelect ($driverId,$isJump,$jumpUrl) {
		if(checkQualified(1000) or checkDispatcher()) {
			if($isJump) {
				print "	<form name=\"jumpDriver\">
	  <select name=\"menu1\" onChange=\"MM_jumpMenu('parent',this,0)\">\n";
	  		} else {
				print "		  <select name=\"driverId\">";
			}

				$driver_sql = "SELECT `driver_id` , concat( `lastname` , \", \", `firstname` ) AS name FROM t_drivers WHERE `terminated` IS NULL ORDER BY `lastname` ASC, `firstname` ASC";
				$driver = mysql_query($driver_sql);
				while($driver_data = mysql_fetch_assoc($driver)) {
					if($driver_data['driver_id'] == $driverId) {
						$selected = ' selected';
					} else {
						$selected = '';
					}
					print "    <option value=\"" . $jumpUrl . $driver_data['driver_id'] . '"' . $selected . ">" . $driver_data['name'] . "</option>\n";
				}
				mysql_free_result($driver);
			?>
		  </select>
			<?php
			if($isJump)
				print "</form>";
		} else {
			print $_SESSION['firstname'] . " " . $_SESSION['lastname'];
		}
	}
	
	function checkDispatcher() {
		if($_SERVER['REMOTE_ADDR'] == DISPATCH_IP && DISPATCHERS_ARE_SPECIAL && checkQualified("1000")) {
			return true;
		} else {
			return false;
		}
	}
	
	function displayIcon ($icon) {
		return "<img src='$icon' height=16 width=16 border=0 alt='icon'>";
	}

	function exclusionActiveDriver ($driver) {  //returns true or false for this driver
		//just check if this driver has an active exclusion
		$result = mysql_query("SELECT * FROM `t_sched_groups` WHERE `exclusive_lock_driver` = " . $driver . " AND `exclusive_lock_expire` > " . time());
		if(mysql_num_rows($result) > 0) {
			return true;
		} else {
			return false;
		}
	}
	function exclusionActiveGroup ($group) {  //returns false if no exclusion, returns the driver_id if exclusion
		//just check if this driver has an active exclusion
		$result = mysql_query("SELECT * FROM `t_sched_groups` WHERE `group_id` = " . $group . " AND `exclusive_lock_expire` > " . time());
		if(mysql_num_rows($result) > 0) {
			$data2 = mysql_fetch_assoc($result);
			return $data2['exclusive_lock_driver'];
		} else {
			return false;
		}
	}
	function exclusionActiveExpire ($group) {
		//just check when this exclusion ends..
		$result = mysql_query("SELECT * FROM `t_sched_groups` WHERE `group_id` = " . $group );
		if(mysql_num_rows($result) > 0) {
			$data2 = mysql_fetch_assoc($result);
			return date("g:i a",$data2['exclusive_lock_expire']);
		} else {
			return false;
		}
	}
	
	function driverName ($driver_id) {
		if($driver_id == -1)
			return "System";
		$sql = sprintf("SELECT `firstname`,`lastname` FROM `t_drivers` WHERE `driver_id` = %s",quote_smart($driver_id));
		$result = mysql_query($sql);
		printMYSQLDebug($sql,$result);
		if($result === false) {
			printDebug("Error querying for driver.",LVL_ERROR,"MySQL said: " . mysql_errno() . " " . mysql_error(),1);
			return "Error.";
		}
		if(@mysql_num_rows($result) == 1) {
			$driver_data = mysql_fetch_assoc($result);
			return $driver_data['firstname'] . ' ' . $driver_data['lastname'];
		}
		return "Invalid Driver";
	}

	function driverDetail ($driver_id,$detail) {
		$result = mysql_query("SELECT * FROM `t_drivers` WHERE `driver_id` = " . $driver_id);
		if(mysql_num_rows($result) == 1) {
			$data = mysql_fetch_assoc($result);
			return $data[$detail];
		}
		return false;
	}

	function writeAjaxUpdateField ($name,$initialValue,$spanName) {
		?>
	<span id="<?=$spanName?>"><?= $initialValue ?><span style="font-size:10px; font-weight:bold; padding-left:5px; ">[ <a href="javascript:editField('<?=$name?>','<?=$initialValue?>','<?=$spanName?>')">EDIT</a> ]</span></span>
		<?php
	}

	function updateDetail ($table,$detail,$where,$value) {
		$sql = "UPDATE `" . $table . "` SET `" . $detail . "` = " . quote_smart($value) . " WHERE " . $where;
		$result = mysql_query($sql);
		if(mysql_affected_rows() == 1) {
			return true;
		}
		return "MySQL Said: " . mysql_errno() . " - " . mysql_error() . " (" . $sql . ")";
	}	

	function check_email_address($email) {
		// First, we check that there's one @ symbol, and that the lengths are right
		if (!ereg("^[^@]{1,64}@[^@]{1,255}$", $email)) {
			// Email invalid because wrong number of characters in one section, or wrong number of @ symbols.
			return false;
		}
		// Split it into sections to make life easier
		$email_array = explode("@", $email);
		$local_array = explode(".", $email_array[0]);
		for ($i = 0; $i < sizeof($local_array); $i++) {
			if (!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$", $local_array[$i])) {
				return false;
			}
		}
		if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1])) { // Check if domain is IP. If not, it should be valid domain name
			$domain_array = explode(".", $email_array[1]);
			if (sizeof($domain_array) < 2) {
				return false; // Not enough parts to domain
			}
			for ($i = 0; $i < sizeof($domain_array); $i++) {
				if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$", $domain_array[$i])) {
					return false;
				}
			}
		}
		return true;
	}
	function formatPhone ($phone) {
		//receive a phone number in 10digit format (ie  8608611750) and format it to (860) 861-1750
		return "(" . substr($phone,0,3) . ") " . substr($phone,3,3) . "-" . substr($phone,6,4);
	}
	function formatDate ($dateString) {
		//receive a date in 20040608 format and return June 8th, 2004
		return date("M jS, Y",mktime(0,0,0,substr($dateString,4,2),substr($dateString,6,2),substr($dateString,0,4)));
	}
	function formatDate_short ($dateString) {
		//receive a date in 20040608 format and return 06/08/04
		return date("m/d/y",mktime(0,0,0,substr($dateString,4,2),substr($dateString,6,2),substr($dateString,0,4)));
	}
	function formatDate_long ($dateString) {
		//receive a date in 20040608 format and return June 8th, 2004
		return date("l, F jS, Y",mktime(0,0,0,substr($dateString,4,2),substr($dateString,6,2),substr($dateString,0,4)));
	}
	
	function sendEmail ($to,$from,$subject,$body) {
	
		$email_body = '
<html>
<head>
  <title>Test Transpo Email</title>
</head>
<body>
  <table border="0" style="padding:0px;" cellpadding="0" cellspacing="0">
    <tr>
      <td><img src="http://transpo.uconn.edu/images/blue_top.gif"></td>
      <td><img src="http://transpo.uconn.edu/images/banner.jpg"></td>
    </tr>
    <tr>
      <td colspan="2">
	    <table width="850"  border="0" cellspacing="5" cellpadding="0" style="border: 2px solid #000066;">
		  <tr>
		    <td>
' . $body . '
			  <p style="margin: 10px; " align="center">&nbsp;</p>
			  <hr>
			  <p style="margin: 10px; font-size:10px">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;This e-mail has been sent automatically by the Transportation Online System. It has been sent to ' . $to . '. To change this address, please login <a href="http://transpo.uconn.edu/">here</a>.</p>
			</td>
		  </tr>
		</table>
	  </td>
    </tr>
  </table>
</body>
</html>
';		
		mail($to,$subject,$email_body,"From: $from\r\nContent-type: text/html; charset=iso-8859-1");
	}
	
	function sendText($driverId,$text) {
		print "Text messaging module not complete.";
	}

	function generatePassword () {
		$length = 8;
		$password = "";
		// possible characters
		$possible = "0123456789bcdfghjkmnpqrstvwxyz"; 
		$i = 0; 
		while ($i < $length) { 
			// pick a random character from the possible ones
			$char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
				
			// we don't want this character if it's already in the password
			if (!strstr($password, $char)) { 
				$password .= $char;
				$i++;
			}
		} 
		return $password;
	}

	function printVersion() {
		print "1.26  rel. 5/26/2007";
	}
?>